<?php include "../public/header.php";?>
<?php include "../public/header_edit.php";?>
<style>
    .mintits{display: inline-block;width: 100%;margin: 0 0 5px 0}
    .mindot{width: 5px;height: 5px;margin-top: 7px;background-color: #525967;border-radius: 50%;float: left;margin-right: 10px}
    .tab_wrapper{width: calc(100% - 40px);height: 380px;padding: 20px 20px 0;overflow: auto}
    .tab_wrapper table td{width: 170px!important;}
    .tab_wrapper table thead th{background-color: #ccd5f1}
    .tab_wrapper table td.active{border: 2px solid #0db3a6!important;}
    .layui-table td{height: 20px}
</style>
<body>
<form class="layui-form layui-form-pane" id="operatePage">
    <div class="page-title"><div class="page-title-con">
            <span>粘贴新增</span>
            <div class="page-title-opt-list">
                <button type="button" class="layui-btn layui-btn-sm btn-dark marginr5" lay-submit="" lay-filter="add">提交</button>
                <span id="page-close" class="page-close" onclick="layer_close()">×</span>
            </div>
        </div>
    </div>
    <div class="main-container" style="margin: 0 15px;">
        <div class="mintits"><div class="mindot"></div><div>使用快捷键 ctrl + v 将Excel内容直接粘贴至表格中，使用 ctrl + z 撤销粘贴操作</div></div>
        <div class="mintits"><div class="mindot"></div><div>已自动隐藏不支持粘贴的字段列，请注意对应字段顺序</div></div>
        <div class="mintits"><div class="mindot"></div><div>当前子表单总行数不可超过200行</div></div>
        <div class="mintits"><div class="mindot"></div><div>不符合该列格式的数据将直接清空</div></div>
    </div>


    <div class="tab_wrapper">
        <table class="layui-table" id="tabcons">
            <thead><tr id="headcons"></tr></thead>
            <tbody id="bodycons"></tbody>
        </table>
    </div>

</form>
<script>
    var param_ctrlv_field_name = getQueryVariable('ctrlv_field_name') || '';
    var param_ctrlv_data_show = getQueryVariable('ctrlv_data_show') || '';
    var fieldarr = parent[param_ctrlv_field_name];
    var pubsubdata = [];
    var activeCellIndex = 0;
    var activeRowIndex = 1;



    layui.use(['laytp', 'form'], function() {
        var form = layui.form, layer = layui.layer;

        var tabwid = parseInt( fieldarr.length * 170 );
        $("#tabcons").css('width', tabwid+'px');

        //表头处理
        var headstr = '';
        for (var key in fieldarr) {
            headstr += '<th key="'+fieldarr[key].field+'">'+fieldarr[key].name+'</th>';
        }
        $("#headcons").html(headstr);


        init_pubdata();
        upd_tab_data();





        window.addEventListener("paste", function (e) {
            var xuanobj = $("#bodycons tr").children('.active');
            if(xuanobj.length < 1){
                facade.error('请选择要插入的表格行');return false;
            }

            if (!(e.clipboardData && e.clipboardData.items)) {
                return;
            }


            // for (var i = 0, len = e.clipboardData.items.length; i < len; i++) {
            //     var itemz = e.clipboardData.items[i];
            //     if (itemz.kind === "string") {
            //         itemz.getAsString(function (str) {
            //             console.log(str)
            //             // console.log(str.search('Microsoft Excel'))
            //             // if ( str.search('Microsoft Excel') )!= false ){
            //             //     console.log(str)
            //             // }
            //         })
            //     }
            // }
            // return false;


            var html = e.clipboardData.getData('text/html');
            var $doc = new DOMParser().parseFromString(html,'text/html');
            if(html.search('Microsoft Excel') != -1){

                var ctrlArr = [];

                $( $doc.querySelectorAll('table tr') ).each(function () {
                    var chilhang = [];
                    $( $(this).children('td') ).each(function () {
                        chilhang.push($(this).text());
                    });
                    ctrlArr.push(chilhang)
                });

                chu_new_data(ctrlArr)
            }
        })





        function KeyPress(e) {
            var evtobj = window.event ? event : e
            if (evtobj.keyCode == 26 && evtobj.ctrlKey){
                if(pubsubdata.length > 1){
                    pubsubdata.pop()
                    upd_tab_data()
                }
            }
        }
        document.onkeypress = KeyPress;




        form.on('submit(add)', function(data){
            var list = [];
            try {
                $('#bodycons tr').each(function (i) {
                    var hhhobj = {};
                    var checkhang = false;
                    $(this).children('td').each(function (key, val) {
                        var _value = $(this).text();
                        hhhobj[fieldarr[key].field] = _value
                        if(_value){
                            checkhang = true
                        }
                    });
                    if(checkhang){
                        list.push(hhhobj)
                    }

                });
            } catch(e) {
                return false;
            }

            if(list.length > 0){
                parent[param_ctrlv_data_show](list);
                layer_close();
            }else{
                facade.error("请复制粘贴excel数据！")
                return false;
            }

            return false;
        });

    });











    function chu_new_data(data) {
        var newArr = JSON.parse(pubsubdata[pubsubdata.length - 1]);

        for (var mm in data) {
            for (var nn in data[mm]) {
                var one = parseInt(activeRowIndex)-1+parseInt(mm)
                var two = parseInt(activeCellIndex)+parseInt(nn)
                if(one < 200 && two < fieldarr.length){
                    if(one >= Object.keys(newArr).length){
                        newArr[one] = get_nulljsonobj();
                    }
                    newArr[one][two] = data[mm][nn]
                }
            }
        }

        pubsubdata.push(JSON.stringify(newArr))
        upd_tab_data();
    }

    function upd_tab_data() {
        $("#bodycons").html('');
        var data = JSON.parse(pubsubdata[pubsubdata.length - 1]);
        var hangstr = '';
        for (var mm in data) {
            var str = '<tr>';
            for (var nn in data[mm]) {
                str += '<td>'+qingxi_data(data[mm][nn], nn)+'</td>';
            }
            str += '</tr>'
            hangstr += str;
        }
        $("#bodycons").append(hangstr);
        $("#bodycons tr td").click(function () {
            $("#bodycons tr td").removeClass('active');
            $(this).addClass('active');
            activeCellIndex = $(this)[0].cellIndex;
            activeRowIndex = $(this).parent('tr')[0].rowIndex;
        });


        var rownum = activeRowIndex;
        var cellnum = parseInt(activeCellIndex)+1;
        $("#bodycons tr:nth-child("+rownum+") td:nth-child("+cellnum+")").addClass('active');
    }

    function init_pubdata() {
        var arr = {};
        var _arr = {};
        for (var i = 0; i < fieldarr.length; i++) {
            _arr[i] = '';
        }
        for (var m = 0; m < 10; m++) {
            arr[m] = _arr;
        }
        pubsubdata.push(JSON.stringify(arr))
    }


    function get_nulljsonobj() {
        var arr = {};
        var _arr = {};
        for (var i = 0; i < fieldarr.length; i++) {
            _arr[i] = '';
        }
        return _arr;
    }



    function qingxi_data(value, key) {
        var type = fieldarr[key].type || '';
        if(type == 'number'){
            value = parseFloat(value) || '';
        }
        if(type == 'date'){
            value = zhuan_str_date(value);
        }
        return value;
    }

</script>
</body>
</html>
